/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Vben、ThinkGem
 */
import type { UserInfo } from '/#/store';
import type { ErrorMessageMode } from '/#/axios';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/enums/roleEnum';
import { PageEnum } from '/@/enums/pageEnum';
import { TOKEN_KEY, ROLES_KEY, USER_INFO_KEY, SESSION_TIMEOUT_KEY } from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { loginApi, logoutApi, userInfoApi, LoginParams, LoginResult } from '/@/api/sys/login';
// import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { usePermissionStore } from '/@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { useGlobSetting } from '/@/hooks/setting';
import logoImg from '/@/assets/images/logo.png';
import mitt, { Emitter } from '/@/utils/mitt';

const { showMessage, createConfirm } = useMessage();

// === New: robust, URL-safe path normalizer (pathnames only) ===
function normalizePath(p: string | undefined | null): string {
  let path = (p || '').trim();

  // If full URL, extract pathname first to avoid breaking protocol "http://"
  if (path.startsWith('http')) {
    try {
      const u = new URL(path);
      path = u.pathname || '/';
    } catch {
      // fall back to as-is
    }
  }

  // Collapse multiple slashes *inside* the pathname
  path = path.replace(/\/{2,}/g, '/');

  // Ensure leading slash
  if (!path.startsWith('/')) path = '/' + path;

  return path;
}

// Remove duplicate publicPath prefix from a given pathname
function stripPublicPathPrefix(pathname: string, publicPath: string): string {
  const pp = (publicPath || '/').replace(/\/+$/g, ''); // remove trailing /
  if (pp && pp !== '/' && pathname.startsWith(pp + '/')) {
    return pathname.slice(pp.length);
  }
  return pathname;
}

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: RoleEnum[] | string[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  pageCache: any;
  emitter: Emitter;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // roleList
    roleList: [],
    // Whether the login expired
    sessionTimeout: undefined,
    // Last fetch time
    lastUpdateTime: 0,
    // 刷新页面及销毁的缓存
    pageCache: {},
    // 全局事件 think gem
    emitter: mitt(),
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {} as any;
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
    getRoleList(): RoleEnum[] | string[] {
      return this.roleList.length > 0
        ? this.roleList
        : getAuthCache<RoleEnum[] | string[]>(ROLES_KEY);
    },
    getSessionTimeout(): boolean {
      return !!(this.sessionTimeout || getAuthCache<boolean>(SESSION_TIMEOUT_KEY));
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
    getPageCache(): any {
      return this.pageCache;
    },
    getEmitter(): any {
      return this.emitter;
    },
  },
  actions: {
    setToken(token: string | undefined) {
      this.token = token ? token : ''; // for null or undefined value
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(TOKEN_KEY, token);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
      setAuthCache(SESSION_TIMEOUT_KEY, flag);
    },
    setUserInfo(res: Recordable | null) {
      const info: UserInfo = res?.user;
      if (res && info) {
        const { ctxPath } = useGlobSetting();
        let url = info.avatarUrl || '/ctxPath/static/images/user1.jpg';
        url = url.replace('/ctxPath/', ctxPath + '/');
        info.avatarUrl = url || logoImg;

        // ——— KEY FIX: normalize homePath / desktopUrl before storing ———
        if ((res as any).desktopUrl) {
          info.homePath = normalizePath((res as any).desktopUrl);
        } else if (info.homePath) {
          info.homePath = normalizePath(info.homePath as any);
        }

        info.roleList = (res as any).roleList;
      }
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    setRoleList(roleList: RoleEnum[] | string[]) {
      this.roleList = roleList;
      setAuthCache(ROLES_KEY, roleList);
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = true;
    },
    setPageCache(key: string, value: any) {
      this.pageCache[key] = value;
    },
    getPageCacheByKey(key: string, defaultValue?: any): any {
      if (!this.pageCache[key] && defaultValue) {
        this.pageCache[key] = defaultValue;
      }
      return this.pageCache[key];
    },
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ) {
      const { goHome = true, mode, ...loginParams } = params;
      const res = await loginApi(loginParams, mode);
      if ((res as any).result !== 'true' && (res as any).result !== true) {
        showMessage((res as any).message);
        this.initPageCache(res);
        return res;
      }
      this.setUserInfo(res);
      this.initPageCache(res);
      this.setSessionTimeout(false);
      await this.afterLoginAction(res, goHome);
      return res;
    },
    // async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
    async afterLoginAction(res: LoginResult, goHome?: boolean) {
      if (!this.getToken) return null;
      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        // this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        if (!permissionStore.isDynamicAddedRoute) {
          try {
            const routes = await permissionStore.buildRoutesAction();
            if (routes && routes.length > 0) {
              routes.forEach((route) => {
                router.addRoute(route as unknown as RouteRecordRaw);
              });
              router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
              permissionStore.setDynamicAddedRoute(true);
            }
          } catch (error) {
            console.error('添加动态路由失败:', error);
          }
        }
        if (goHome) {
          const currentRoute = router.currentRoute.value;
          let path: any = (currentRoute.query as any).redirect || (res as any).user?.homePath || PageEnum.BASE_HOME;

          // If full URL, take pathname
          try {
            if (typeof path === 'string' && path.startsWith('http')) {
              const url = new URL(path);
              path = url.pathname;
            }
          } catch (e) {
            console.warn('Invalid URL format in redirect/homePath:', path);
          }

          // Handle VITE_PUBLIC_PATH duplication only on pathname
          const rawPublicPath = (import.meta.env.VITE_PUBLIC_PATH || '/') as string;
          path = stripPublicPathPrefix(String(path), rawPublicPath);

          // Final normalize
          path = normalizePath(String(path));

          // If normalized to root, prefer BASE_HOME when defined
          if (path === '/' && PageEnum.BASE_HOME) {
            path = normalizePath(PageEnum.BASE_HOME as any);
          }

          // Debug (optional):
          // console.table({ rawPublicPath, finalPath: path });
        if (typeof path === 'string') {
            path = path.replace(/\/{2,}/g, '/');
          }
          await router.replace(decodeURIComponent(path as string));
        }
        if ((res as any)['modifyPasswordTip']) {
          createConfirm({
            content: (res as any)['modifyPasswordTip'],
            maskClosable: false,
            iconType: 'info',
            cancelText: '取消',
            okText: '确定',
            onOk: () => {
              router.replace('/account/modPwd');
            },
          });
        }
      }
      return (res as any).user || null;
    },
    async getUserInfoAction() {
      // if (!this.getToken) return null;
      const res = await userInfoApi();
      this.setUserInfo(res);
      this.initPageCache(res);
      // this.setRoleList(roleList);
      this.setSessionTimeout(false);
      return (res as any).user;
    },
    initPageCache(res: LoginResult) {
      this.setPageCache('demoMode', (res as any).demoMode);
      this.setPageCache('useCorpModel', (res as any).useCorpModel);
      this.setPageCache('modifyPasswordTip', (res as any).modifyPasswordTip);
      this.setPageCache('modifyPasswordMsg', (res as any).modifyPasswordMsg);
      this.setPageCache('sysCode', (res as any).sysCode);
      this.setPageCache('roleCode', (res as any).roleCode);
      this.setPageCache('title', (res as any).title);
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await logoutApi();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(undefined);
      this.setSessionTimeout(true);
      this.setUserInfo(null);
      this.setRoleList([]);
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },
    /**
     * @description: Confirm before logging out
     */
    async confirmLoginOut() {
      await this.logout(true);
    },
  },
});

// Global emit by think gem
export function useEmitter() {
  return useUserStore().emitter;
}

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
